package validator

import (
	"a_plus_station/global"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

func removeKey(fields map[string]string) string {
	//rsp := map[string]string{}
	rsp := ""
	for _, err := range fields {
		//fmt.Println(fields,err)
		// strings.Index，fields是原始字符串，"."是我们要查找索引值的字符串
		//rsp[fields[strings.Index(fields,".")+1:]] = err
		rsp += err
		break
	}
	return rsp
}

func HandleValidatorError(ctx *gin.Context, err error) {
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		ctx.JSON(http.StatusForbidden, gin.H{
			"msg": err.Error(),
		})
		return
	}

	//fmt.Println(err.Error())
	ctx.JSON(http.StatusForbidden, gin.H{
		"msg": removeKey(errs.Translate(global.Trans)),
	})
	return
}
